<template>
  <div>
    <!-- 面包屑  -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片视图  -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input clearable
                    placeholder="请输入内容"
                    v-model="queryInfo.query"
                    class="input-with-select"
                    @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        border
        stripe
        :data="userList">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column width="180" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <el-tooltip content="分配角色" placement="top" effect="dark" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--  分页    -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--  添加用户的对话框  -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose">
      <!--  内容主体区域    -->
      <el-form ref="addUserRef"
               :model="addUserForm"
               :rules="addUserRules"
               label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input type="password"
                    v-model="addUserForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--  对话框底部区域    -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--  修改用户  -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose">
      <!--  内容主体区域    -->
      <el-form ref="editUserRef"
               :model="editUserForm"
               :rules="editUserRules"
               label-width="70px">
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="editUserForm.username"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--  分配用户角色  -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed">
      <!--  内容主体区域    -->
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data () {
      //  验证邮箱规则
      const checkEmail = (rules, value, cb) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          return cb() // 返回调用的回调函数表示校验通过
        }
        return cb(new Error('请输入合法的邮箱'))
      }
      // 验证手机号规则
      const checkMobile = (rules, value, cb) => {
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          return cb() // 返回调用的回调函数表示校验通过
        }
        return cb(new Error('请输入合法的手机号'))
      }
      return {
        // 获取用户列表参数对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },
        // 用户列表
        userList: [],
        // 总的数据长度
        total: 0,
        // 控制添加用户对话框的使用
        addDialogVisible: false,
        // 添加用户的表单数据
        addUserForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 修改用户对话框显示
        editDialogVisible: false,
        // 查询到的用户信息对象
        editUserForm: {},
        // 添加用户验证规则
        addUserRules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
            {
              min: 3,
              max: 10,
              messge: '用户名的长度在3和10之间',
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 15,
              message: '长度在6到15个字符',
              trigger: 'blur'
            }
          ],
          email: [
            {
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            }, {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [
            {
              required: true,
              message: '请输入手机',
              trigger: 'blur'
            }, {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        },
        editUserRules: {
          email: [
            {
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            }, {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [
            {
              required: true,
              message: '请输入手机',
              trigger: 'blur'
            }, {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        },
        // 控制添加用户角色对话框显示
        setRoleDialogVisible: false,
        // 需要被分配权限的用户信息
        userInfo: {},
        // 所有角色的列表
        rolesList: [],
        // 选中的角色id
        selectedRoleId: ''
      }
    },
    methods: {
      async getUserList () {
        const { data: res } = await this.$http.get('users', { params: this.queryInfo })
        if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
        this.userList = res.data.users
        this.total = res.data.total
      },
      // pageSize改变事件
      handleSizeChange (newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 页面值改变事件
      handleCurrentChange (newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // swtich开关状态改变事件
      async userStateChange (userInfo) {
        const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('更新用户状态失败')
        }
        this.$message.success('更新用户状态成功')
      },
      // 添加用户对话框关闭事件
      addDialogClose () {
        this.$refs.addUserRef.resetFields()
      },
      // 添加用户方法
      addUser () {
        this.$refs.addUserRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.post('users', this.addUserForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加用户失败！')
          }
          this.$message.success('添加用户成功！')
          // 隐藏对话框
          this.addDialogVisible = false
          // 刷新用户列表
          this.getUserList()
        })
      },
      // 修改用户对话框关闭事件
      editDialogClose() {
        this.$refs.editUserRef.resetFields()
      },
      // 修改用户事件
      editUser() {
        this.$refs.editUserRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.put('users/' + this.editUserForm.id, {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          })
          if (res.meta.status !== 200) {
            this.$message.error('修改用户失败！')
          }
          this.$message.success('修改用户成功！')
          // 隐藏对话框
          this.editDialogVisible = false
          // 刷新用户列表
          this.getUserList()
        })
      },
      // 展示编辑用户窗口
      async showEditDialog (id) {
        const { data: res } = await this.$http.get('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('查询用户信息失败！')
        this.editUserForm = res.data
        this.editDialogVisible = true
      },
      // 根据id删除用户
      async removeUser(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户成功')
        this.getUserList()
      },
      // 分配角色按钮事件
      async setRole(userInfo) {
        this.userInfo = userInfo
        const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败！')
        }
        this.rolesList = res.data

        this.setRoleDialogVisible = true
      },
      // 点击分配角色
      async saveRoleInfo() {
        if (!this.selectedRoleId) return this.$message.error('请选择要分配的角色！')
        const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
        if (res.meta.status !== 200) return this.$message.error('更新角色失败')
        this.$message.success('更新角色成功！')
        this.getUserList()
        this.setRoleDialogVisible = false
      },
      // 分配角色对话框关闭事件
      setRoleDialogClosed() {
        this.selectedRoleId = ''
        this.userInfo = {}
      }
    },
    created () {
      this.getUserList()
    }
  }
</script>

<style lang="less" scoped>

</style>
